package api

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math"
	"net/http"
	"strconv"
	"strings"
	. "xm_shop/database"
	. "xm_shop/models"
)

type ProductController struct{}

// 检索商品分类对应的商品数据
func (p ProductController) Category(context *gin.Context) {
	cateId, err1 := strconv.Atoi(context.Param("id"))
	if err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 当前页面
	page, err2 := strconv.Atoi(context.Query("page"))
	if err2 != nil || page <= 0 {
		page = 1
	}
	// 每页的数据量
	pageSize := 5

	// 检索数据
	var goodsCate GoodsCate
	DB.Where("id = ?", cateId).Find(&goodsCate)
	var subCateList []GoodsCate
	var tempSlice []int
	if goodsCate.Pid == 0 { // 如果的顶级分类, 检索二级分类
		// 检索次级分类
		DB.Where("pid = ?", goodsCate.ID).Find(&subCateList)
		// 统计id
		for i := 0; i < len(subCateList); i++ {
			tempSlice = append(tempSlice, subCateList[i].ID)
		}
	} else { // 不是顶级分类, 检索兄弟分类
		DB.Where("pid = ?", goodsCate.Pid).Find(&subCateList)
	}
	tempSlice = append(tempSlice, goodsCate.ID) // 最后打入当前分类的ID
	// 检索所属分类的商品
	var goodsList []Goods
	DB.Where("cate_id in ?", tempSlice).Offset((page - 1) * pageSize).Limit(pageSize).Find(&goodsList)

	var topNavList []Nav
	// 获取顶部导航栏redis
	if flag := CacheDB.Get("topNavList", &topNavList); !flag {
		DB.Where("status = ? AND position = ?", 1, 1).Find(&topNavList) // 检索数据库
		CacheDB.Set("topNavList", topNavList, 60*60)
	}
	var middleNavList []Nav
	// 获取中间导航栏
	if flag := CacheDB.Get("middleNavList", &middleNavList); !flag {
		DB.Where("status = ? AND position = ?", 1, 2).Find(&middleNavList)
		CacheDB.Set("middleNavList", middleNavList, 60*60) // 打入缓存
	}
	for i := 0; i < len(middleNavList); i++ {
		// 中文转换
		relation := strings.ReplaceAll(middleNavList[i].Relation, "，", ",")
		//切片
		relationIds := strings.Split(relation, ",")
		var goodsList []Goods
		// 检索关联商品
		DB.Where("id in ?", relationIds).Select("id,title,goods_img,price").Find(&goodsList)
		// 填充
		middleNavList[i].GoodsItems = goodsList
	}
	var goodsCateList []GoodsCate
	// 获取顶级分类和次级分类redis
	if flag := CacheDB.Get("goodsCateList", &goodsCateList); !flag {
		DB.Where("pid = ? AND status = ?", 0, 1).Preload("GoodsCateItems", func(DB *gorm.DB) *gorm.DB {
			return DB.Where("goods_cate.status = ?", 1).Order("goods_cate.sort DESC")
		}).Order("sort DESC").Find(&goodsCateList)
		CacheDB.Set("goodsCateList", goodsCateList, 60*60) // 打入缓存
	}

	// 获取总数量
	var count int64
	DB.Table("goods").Where("cate_id in ?", tempSlice).Count(&count)

	context.JSON(http.StatusOK, gin.H{
		"topNavList":    topNavList,
		"middleNavList": middleNavList,
		"goodsCateList": goodsCateList,
		"goodsList":     goodsList,
		"subCateList":   subCateList, // 二级分类
		"totalPages":    math.Ceil(float64(count) / float64(pageSize)),
		"page":          page,
	})
}

// 商品详细
func (p ProductController) Detail(context *gin.Context) {
	id, err1 := strconv.Atoi(context.Query("id"))
	if err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 1. 检索商品
	var goods Goods
	DB.Where("id = ?", id).Take(&goods)

	// 2. 获取关联商品
	var relationGoods []Goods
	relationStr := strings.ReplaceAll(goods.RelationGoods, "，", ",")
	//切片
	relationIds := strings.Split(relationStr, ",")
	// 检索关联商品
	DB.Where("id in ?", relationIds).Select("id,title,price,goods_version").Find(&relationGoods)

	// 3. 获取关联赠品
	var goodsGift []Goods
	giftStr := strings.ReplaceAll(goods.GoodsGift, "，", ",")
	giftIds := strings.Split(giftStr, ",")
	// 检索赠品
	DB.Where("id in ?", giftIds).Select("id,title,price,goods_version").Find(&goodsGift)

	// 4. 获取关联配件
	var goodsFitting []Goods
	goods.GoodsFitting = strings.ReplaceAll(goods.GoodsFitting, "，", ",")
	//切片
	fittingIds := strings.Split(goods.GoodsFitting, ",")
	DB.Where("id in ?", fittingIds).Find(&goodsFitting)

	// 5. 获取关联颜色
	var goodsColor []GoodsColor
	goods.GoodsColor = strings.ReplaceAll(goods.GoodsColor, "，", ",")
	//切片
	colorIds := strings.Split(goods.GoodsColor, ",")
	DB.Where("id in ?", colorIds).Find(&goodsColor)

	// 6.获取商品关联的图片
	var goodsImage []GoodsImage
	DB.Where("goods_id = ?", id).Limit(6).Find(&goodsImage)

	//7. 获取规格参数信息
	var goodsAttr []GoodsAttr
	DB.Where("goods_id = ?", id).Find(&goodsAttr)

	// 8. 获取更多属性
	//goodsAttrStr := "尺寸:41,42,43|套餐:套餐1,套餐2"
	goodsAttrStr := goods.GoodsAttr
	// 中文转换
	goodsAttrStr = strings.ReplaceAll(goodsAttrStr, "，", ",")
	goodsAttrStr = strings.ReplaceAll(goodsAttrStr, "：", ":")

	var goodsItemsAttrList []GoodsItemAttr   // 这里并没有分配空间
	if strings.Contains(goodsAttrStr, ":") { // 至少有一个额外属性
		goodsAttrStrSlice := strings.Split(goodsAttrStr, "|")
		// 创建切片的存储空间
		goodsItemsAttrList = make([]GoodsItemAttr, len(goodsAttrStrSlice))

		for i := 0; i < len(goodsAttrStrSlice); i++ {
			tempSlice := strings.Split(goodsAttrStrSlice[i], ":")
			goodsItemsAttrList[i].Cate = tempSlice[0]
			goodsItemsAttrList[i].List = strings.Split(tempSlice[1], ",")
		}
	}

	context.JSON(http.StatusOK, gin.H{
		"goods":              goods,
		"relationGoods":      relationGoods,
		"goodsFitting":       goodsFitting,
		"goodsColor":         goodsColor,
		"goodsImage":         goodsImage,
		"goodsAttr":          goodsAttr,
		"goodsGift":          goodsGift,
		"goodsItemsAttrList": goodsItemsAttrList,
	})
}

// 获取指定商品和颜色对应的图片列表
func (p ProductController) GetImgList(context *gin.Context) {
	goodsId, err1 := strconv.Atoi(context.Query("goods_id"))
	colorId, err2 := strconv.Atoi(context.Query("color_id"))
	if err1 != nil || err2 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	var goodsImageList []GoodsImage
	DB.Where("goods_id = ? AND color_id = ?", goodsId, colorId).Find(&goodsImageList)
	// 判断goodsImageList的长度, 如果没有数据, 则返回商品的所有图片
	if len(goodsImageList) == 0 {
		DB.Where("goods_id = ?", goodsId).Find(&goodsImageList)
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
		"result":  goodsImageList,
		"message": "获取数据成功",
	})
}
